<?php

namespace Xin\WorkmanServer;

use Workerman\Worker;
use Xin\Capsule\WithConfig;
use Xin\Support\Arr;

abstract class Server
{
    use WithConfig;

    /**
     * @var array
     */
    protected $config;

    /**
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;
    }


    /**
     * 解析绑定地址
     * @param array $config
     * @return string
     */
    protected function resolveBindAddress(array $config)
    {
        $bindAddress = Arr::get($config, 'bind_address');
        if (!$bindAddress) {
            $bindHost = Arr::get($config, 'bind_host', '0.0.0.0');
            $bindPort = Arr::get($config, 'bind_port');
            $bindAddress = $bindHost . ':' . $bindPort;
        }

        return $bindAddress;
    }

    /**
	 * 解析上下文
     * @param array $config
     * @return array
     */
    protected function resolveContext(array $config)
    {
        return Arr::get($config, 'context', []);
    }

    /**
	 * 运行
     * @return void
     */
    abstract public function run();


    /**
	 * 运行所有
     * @return void
     */
    public static function runAll()
    {
        Worker::runAll();
    }

    /**
	 * 停止所有
     * @return void
     */
    public static function stopAll()
    {
        Worker::stopAll();
    }
}
